using System;
using Headspring.Training.Core.Services;

namespace Headspring.Training.Core.Model.StateCommands
{
	public abstract class StateCommandBase : IStateCommand
	{
		protected Employee _currentUser;
		protected WorkOrder _workOrder;

		protected StateCommandBase(WorkOrder workOrder, Employee currentUser)
		{
			_workOrder = workOrder;
			_currentUser = currentUser;
		}

		public abstract string TransitionVerbPastTense { get; }

		public abstract WorkOrderStatus GetBeginStatus();
		public abstract string TransitionVerbPresentTense { get; }


		public bool IsValid()
		{
			bool beginStatusMatches = _workOrder.Status == GetBeginStatus();
			bool currentUserIsCorrectRole = userCanExecute(_currentUser);
			return beginStatusMatches && currentUserIsCorrectRole;
		}

		public void Execute(IStateCommandVisitor commandVisitor)
		{
			preExecute(commandVisitor);
			string currentUserFullName = _currentUser.GetFullName();

			_workOrder.ChangeStatus(GetEndStatus(), _currentUser, DateTime.Now);
			commandVisitor.SaveWorkOrder(_workOrder);
			string loweredTransitionVerb = TransitionVerbPastTense.ToLower();
			string workOrderNumber = _workOrder.Number;
			string message = string.Format("You have {0} work order {1}",
			                               loweredTransitionVerb, workOrderNumber);
			commandVisitor.SendMessage(message);
			Logger.Debug(this,
			          string.Format("{0} has {1} work order {2}", currentUserFullName,
			                        loweredTransitionVerb,
			                        workOrderNumber));
			postExecute(commandVisitor);
		}

		public bool Matches(string commandName)
		{
			return TransitionVerbPresentTense == commandName;
		}

		protected abstract WorkOrderStatus GetEndStatus();
		protected abstract bool userCanExecute(Employee currentUser);

		protected virtual void preExecute(IStateCommandVisitor commandVisitor)
		{
		}

		protected abstract void postExecute(IStateCommandVisitor commandVisitor);
	}
}